<?PHP

class LoginHandler {
    /**
    * IsLoggedIn
    * 
    * Function to check if user is logged in
    * 
    * @return bool | return true if user is logged in, else false
    */
    public function IsLoggedIn() {

        // If the session userName is set, then a user is logged in        
        if (isset($_SESSION['userName'])) {
            return true ;
        }

        return false ;
    }
    /**
    * Function to handle the login
    *
    * @return bool | true if the login succeeded and false if not
    */
	public function DoLogin($userName, $password) {

        // Put some test-users in an array    
        $users = array(
            "user" => "password",
            "user2" => "pass2"
        );

        // Check if the username entered is in the users-list and then if the password matches.
        if(isset($users[$userName]) && $users[$userName] === $password) {

            // Save the username as a session so we can see that the user have logged in
            $_SESSION['userName'] = $userName ;

            return true ;
        }
        
        return false ;
    }
    /** 
    * Handles the logout
    * @return bool | true if the login succeded and false if not
    */
    public function DoLogout() {
        // Unset the session
        unset($_SESSION['userName']) ;

        // Check so the session has been removed
        if(isset($_SESSION['userName']) == false) {
            return true ;
        }

        return false ;
    }
    /**
    * For the automatic tests in the class LoginHandler
    */
    public function Test() {
    
    // Start by logging out, so we have a fresh start
    if($this->DoLogout() !== true) {
        echo "DoLogout test failed";
        return false ;
    }
    
    // Now no-one should be logged in, we test that
    if($this->IsLoggedIn() !== false) {
        echo "IsLoggedIn test failed" ;
        return false ;
    }

    // We try to login with incorrect username and password
    if($this->DoLogin("notCorrect", "nietherThis") !== false) {
        echo "DoLogin test failed" ;
        return false ;
    }

    // And we try with correct username and password
    if($this->DoLogin("user", "password") !== true) {
        echo "DoLogin test failed" ;
        return false ;
    }

    // Now we should be logged in, so it is a good time to test IsLoggedIn again
    if($this->IsLoggedIn() !== true) {
        echo "IsLoggedIn test failed" ;
        return false ;
    }

    // Lets try DoLogout again now that we know that someone is logged in.
    if($this->DoLogout() !== true) {
        echo "DoLogout test failed" ;
        return false ;
    }

    // And try to login again with correct username but wrong password
    if($this->DoLogin("user", "wrongPassword") !== false) {
        echo "DoLogin test failed" ;
        return false ;
    }

    // And if all goes well, return true
    return true ;

    }
}

?>
